package com.example.xlmkotlinwanandroid.network

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.xlmkotlinwanandroid.R
import com.example.xlmkotlinwanandroid.ui.activity.WebActivity

class ArticlePagedListAdapter2(var context: Context?) :
    PagedListAdapter<ArticleResponse2.ArticleBean2, ArticlePagedListAdapter2.ArticlePagedListAdapter2ViewHolder>(
        DIFF_CALLBACK
    ) {


    companion object {
        val DIFF_CALLBACK = object : DiffUtil.ItemCallback<ArticleResponse2.ArticleBean2>() {
            override fun areContentsTheSame(
                oldItem: ArticleResponse2.ArticleBean2,
                newItem: ArticleResponse2.ArticleBean2
            ): Boolean {
                return oldItem.courseId.equals(newItem.courseId)
            }

            override fun areItemsTheSame(
                oldItem: ArticleResponse2.ArticleBean2,
                newItem: ArticleResponse2.ArticleBean2
            ): Boolean {
                return oldItem == newItem
            }
        }
    }


    private val inflater: LayoutInflater = LayoutInflater.from(context)


    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ArticlePagedListAdapter2ViewHolder {
        val itemView = inflater.inflate(R.layout.item_ariticle, parent, false)
        return ArticlePagedListAdapter2ViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ArticlePagedListAdapter2ViewHolder, position: Int) {
        var bean = getItem(position)
        holder.homeAuthor.text = bean?.author
        holder.homeTop.text = bean?.superChapterName
        holder.homeDate.text = bean?.niceDate
        holder.homeContent.text = bean?.title
        holder.homeType2.text = "${bean?.superChapterName}:${bean?.author}"

        //设置点击事件
        holder.itemView.setOnClickListener {
            val intent = Intent(context, WebActivity::class.java)
            intent.putExtra("url", bean?.link)
            intent.putExtra("title", bean?.title)
            context?.startActivity(intent)
        }
    }


    class ArticlePagedListAdapter2ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val homeAuthor: TextView = itemView.findViewById(R.id.item_home_author)
        val homeTop: TextView = itemView.findViewById(R.id.item_home_top)
        val homeNew: TextView = itemView.findViewById(R.id.item_home_new)
        val homeType1: TextView = itemView.findViewById(R.id.item_home_type1)
        val homeDate: TextView = itemView.findViewById(R.id.item_home_date)
        val homeContent: TextView = itemView.findViewById(R.id.item_home_content)
        val homeType2: TextView = itemView.findViewById(R.id.item_home_type2)
    }
}